import { view } from './view-state.js';
window.running = true;
window.lastData = null;

let lastTime = performance.now();
function updateFPS() {
    const now = performance.now();
    const fps = Math.round(1000 / (now - lastTime));
    lastTime = now;
    document.getElementById('fps').textContent = `FPS: ${fps}`;
}

export function connectWebSocket() {
    const ws = new WebSocket("ws://localhost:6661/spec");

    ws.onopen = () => console.log("WebSocket 已连接 → 频谱 + QPSK 实时解调");

    ws.onmessage = ev => {
        if (!window.running) return;

        const msg = JSON.parse(ev.data);

        // ====================== 1. 频谱消息（你原来就有的）======================
        if (msg.type === "spectrum" || msg.data) {  // 兼容你原来的格式
            const data = msg.data || msg.Data;  // 兼容大小写
            const backendCenterFreq = msg.CenterFreq || msg.center_freq || 255.0;

            // 防用户手动改频冲突（你原来的逻辑完全保留）
            if (!window.userHasChangedCenterFreq) {
                const input = document.getElementById('centerFreq');
                if (input) input.value = backendCenterFreq;
                if (window.view) window.view.centerFreq = backendCenterFreq;
            }

            window.lastData = data;
            window.redrawAll(data);
            updateFPS();
        }

        // ====================== 2. 新增：解调消息 ======================
        else if (msg.type === "demod") {
            // 星座图
            if (msg.Constellation && msg.Constellation.length >= 2) {
                drawConstellation(constellationCanvas, msg.Constellation);
            }

            // 比特流
            if (msg.Bits !== undefined) {
                const bitsElement = document.getElementById('demod-bits');
                if (bitsElement) {
                    bitsElement.textContent = "Bits: " + msg.Bits;
                }
            }

            // SNR
            if (msg.SNR !== undefined) {
                const snrElement = document.getElementById('demod-snr');
                if (snrElement) {
                    snrElement.textContent = `SNR: ${msg.SNR.toFixed(1)} dB`;
                }
            }
        }
    };

    ws.onerror = e => console.error("WebSocket 错误:", e);
    ws.onclose = () => {
        console.warn("WebSocket 已断开，3秒后自动重连...");
        setTimeout(connectWebSocket, 3000);
    };

    // 可选：把 ws 挂到 window，方便调试
    window.ws = ws;
}